﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using TravelServer.DTOs;
using TravelServer.Models;
using TravelServer.Services;

namespace TravelServer.Controllers
{
    [Route("api")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        //系统提供的专用于账号的数据操作类
        private readonly UserManager<AppUser> userManager;
        //系统提供的专用于账号登录的专用管理类
        private readonly SignInManager<AppUser> signInManager;
        private readonly IConfiguration configuration;
        private readonly ITouristRoutsRepository trsRepository;
        public AccountController(IConfiguration Configuration, 
            UserManager<AppUser> userManager,
            SignInManager<AppUser> signInManager,
            ITouristRoutsRepository trsRepository)
        {
            this.configuration = Configuration;
            this.userManager = userManager;
            this.signInManager = signInManager;
            this.trsRepository=trsRepository;
        }
        //允许任意访问权限?
        [AllowAnonymous]
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginDto loginDto)
        {
            //1验证账号密码  关闭错误锁定账号
            var result = await signInManager.PasswordSignInAsync(loginDto.Email, loginDto.Password, false, false);
            if (!result.Succeeded )
            {
                return BadRequest();

            }
            //获取用户数据
            var user = await userManager.FindByNameAsync(loginDto.Email);
            //获取用户角色信息
            var roles = await userManager.GetRolesAsync(user);

            //2 JWB
            //header 约定加密算法
            var signitureAlgorithm = SecurityAlgorithms.HmacSha256;
            //payload  
            var claims = new List<Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id)
                
            };
          
            //将角色信息存放到Claim中，用于后期http请求中，系统自动获取角色并判断是否有权限(鉴权)
            foreach (var role in roles) { 
            
                var claim=new Claim(ClaimTypes.Role, role);
                claims.Add(claim);
            }
           
            //signiture  签名
            var secretBytes = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            var sigitureKey = new SymmetricSecurityKey(secretBytes);
            var signingCredentials = new SigningCredentials(sigitureKey, signitureAlgorithm);
            var token = new JwtSecurityToken(
                configuration["Authentication:Issuer"],
                configuration["Authentication:Audience"],
                claims,
                DateTime.UtcNow,
                DateTime.UtcNow.AddDays(1),
                signingCredentials
               );

            var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
            await Task.CompletedTask;
            return Ok(tokenStr);
        }


        [HttpPost("Register")]
        public async Task<IActionResult> Register([FromBody] RegisterDto registerDto)
        {
            //创建user表格实体对象
            var user = new AppUser()
            {
                UserName = registerDto.Email,
                Email=registerDto.Email
            };
            //给密码加密，并保存到数据库
            var result = await userManager.CreateAsync(user, registerDto.Password);
            if (!result.Succeeded && !ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            //初始化一个购物车
            var shopCart = new ShoppingCart()
            {
                Id = Guid.NewGuid(),
                UserId = user.Id,
            };
           await trsRepository.AddShoppingCartAsync(shopCart);
            await trsRepository.SaveDataAsync();
           
            return Ok(result);
        }
    }
}
